package com.dailyblue.java.project.oa.emp.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dailyblue.java.project.oa.commons.bean.Emp;
import com.dailyblue.java.project.oa.commons.service.EmpService;
import com.dailyblue.java.project.oa.commons.util.JsonResult;
import com.dailyblue.java.project.oa.commons.util.ResultTool;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/emp")
@Slf4j   // 输出日志
@CrossOrigin
public class EmpController {

    @Resource
    private EmpService empService;
    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @GetMapping("/ecode/{ecode}")
    public JsonResult<Integer> ecode(@PathVariable("ecode") String ecode) {
        return empService.findEmpByECode(ecode);
    }

    @GetMapping("/phone/{phone}")
    public JsonResult<Integer> phone(@PathVariable("phone") String phone) {
        return empService.findEmpByPhone(phone);
    }

    @GetMapping
    @PreAuthorize("hasAuthority('查询员工')")
    public JsonResult find(Emp emp) {
        log.info("接收的emp是:{}", emp);
        return empService.find(emp);
    }

    @PostMapping
    public JsonResult save(Emp emp) {
        /*log.info("接收的json字符串:{}", json);
        Emp emp = JSONArray.parseObject(json, Emp.class);*/
        log.info("转换的对象是：{}", emp);
        return empService.saveEmp(emp);
    }

    @GetMapping("/{page}")
    public JsonResult find(@PathVariable("page") int page) {
        return empService.find(page);
    }

    @DeleteMapping
    public JsonResult delete(int id, int nowPage, int allPage) {
        return empService.delete(id, nowPage, allPage);
    }

    @DeleteMapping("/quit")
    public JsonResult quit(int id,String desc){
        // 获取到准备离职的这个员工的相关信息
        QueryWrapper<Emp> wrapper = new QueryWrapper<>();
        wrapper.eq("id",id);
        Emp emp = empService.getOne(wrapper);
        emp.setQuitDesc(desc);
        // 离职员工
        empService.removeById(id);
        // 向rocketMQ中将一些信息保存进去
        SendResult result = rocketMQTemplate.syncSend("QUIT:TAGA",JSONArray.toJSONString(emp));
        return ResultTool.success(result);
    }
}
